<?php

namespace IDock\Insurance\JTIC\Response;

use IDock\Http\Response;
use IDock\Printer\SpecialClausesPrinter;

class SpecialClausesResponse extends AllJTICResponse
{

    public $specialClausesList = [];

    public function printerInit(): Response
    {
        $data = $this->getBody();

        $tciList = $data['AppSpecTCIList']['SpecItem'] ?? [];

        if ($tciList and !$this->isTwoDimensionalArray($tciList)) {
            $tciList = [$tciList];
        }

        foreach ($tciList as $datum) {
            $specialClauses = new SpecialClausesPrinter();
            $specialClauses->clauseCode = $datum['SpecNo'] ?? '';
            $specialClauses->clauseName = '';
            $specialClauses->clauseContent = $datum['SpecName'] ?? '';
            $specialClauses->riskType = 'TCI';
            $specialClauses->autoFlag = '0';

            $specialClauses->argc['SpecTemplate'] = $datum['SpecTemplate'] ?? '';
            $specialClauses->argc['SpecCustomValue'] = $datum['SpecCustomValue'] ?? '';
            $this->specialClausesList[] = $specialClauses;
        }

        $vciList = $data['AppSpecVCIList']['SpecItem'] ?? [];

        if ($vciList and !$this->isTwoDimensionalArray($vciList)) {
            $vciList = [$vciList];
        }

        foreach ($vciList as $datum) {
            $specialClauses = new SpecialClausesPrinter();
            $specialClauses->clauseCode = $datum['SpecNo'] ?? '';
            $specialClauses->clauseName =  '';
            $specialClauses->clauseContent = $datum['SpecName'] ?? '';
            $specialClauses->riskType = 'VCI';
            $specialClauses->autoFlag = '0';

            $specialClauses->argc['SpecTemplate'] = $datum['SpecTemplate'] ?? '';
            $specialClauses->argc['SpecCustomValue'] = $datum['SpecCustomValue'] ?? '';
            $this->specialClausesList[] = $specialClauses;
        }

        return $this;
    }

    private function isTwoDimensionalArray($array): bool
    {
        if (!is_array($array)) {
            return false;
        }

        foreach ($array as $element) {
            if (!is_array($element)) {
                return false;
            }
        }

        return true;
    }
}
